'use strict'

const fs = require('fs')
const path = require('path')
const config = require('../config')
const Sequelize = require('sequelize')
const co = require('co')
const sequelize = new Sequelize(config.database, config.dbUser, config.dbPassword, {
  host: config.dbHost,
  port: config.dbPort,
  dialect: 'mysql', // or 'sqlite', 'postgres', 'mariadb'
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  timezone: '+08:00',
  // 请参考 Querying - 查询 操作符 章节
  operatorsAliases: false,
  // logging: false,
  define: {
    timestamps: false
  }
})

let db = {}
const files = fs.readdirSync(__dirname).filter(file => {
  return path.extname(file) === '.js' && file !== 'index.js'
})
files.forEach(file => {
  let model = sequelize.import(path.join(__dirname, file))
  db[path.basename(file, '.js')] = model
})

Object.keys(db).forEach(modelName => {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db)
  }
})
db.sequelize = sequelize
db.Sequelize = Sequelize
db.Article.Category = db.Article.belongsTo(db.Category)
db.Category.Article = db.Category.hasMany(db.Article)
db.Article.ArticleTags = db.Article.belongsToMany(db.Tag, { through: db.ArticleTag, as: 'Tags' })
db.Tag.ArticleTags = db.Tag.belongsToMany(db.Article, { through: db.ArticleTag, as: 'Articles' })
db.Article.Comments = db.Article.hasMany(db.Comments)
db.Comments.User = db.Comments.belongsTo(db.User)
db.Comments.Comments = db.Comments.hasMany(db.Comments)
co(function * () {
  (async () => {
    await sequelize.authenticate()
    await sequelize.sync({ force: false, hooks: true })
  })()
}).catch(e => {
  console.error(e)
})

module.exports = db
